package com.itheima.sh.c_ajax_json;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

@WebServlet("/demo03Servlet")
public class Demo03Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
        try {
            User user = JSON.parseObject(request.getInputStream(), User.class);
            System.out.println(user.getUserName()+"---"+user.getPassword());

            //创建List集合对象
            ArrayList<Friend> list = new ArrayList<>();
            Collections.addAll(list,new Friend(1,"喜洋洋",10),
                                    new Friend(2,"懒洋洋",9),
                                    new Friend(3,"美洋洋",9));
            //创建响应结果类的对象
            Result result = new Result(true,"查询好友列表成功",list);
            //将result对象转换为json格式数据
            String str = JSON.toJSONString(result);
            //响应给前端
            response.getWriter().print(str);
        } catch (Exception e) {
            //打印错误信息到idea控制台
            e.printStackTrace();
            //查询失败
            //创建响应结果类的对象
            Result result = new Result(false, "查询好友列表失败");
            //将result对象转换为json格式数据
            String str = JSON.toJSONString(result);
            //响应给前端
            response.getWriter().print(str);
        }

    }
}
